package com.alex.tinyurl.service.store.mem;

import com.alex.tinyurl.service.store.UrlMappingStore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 内存URL的存储策略，采用内存Map结构存储
 *
 * @author Alex
 */
@Service
@ConditionalOnProperty(prefix = "tinyurl", name = "store.strategy", havingValue = "mem")
public class MemMapUrlMappingStore implements UrlMappingStore {

    public static final int MAP_DEFAULT_SIZE = 1024 * 1024;
    private HashMap<String, String> urlMap = new HashMap<>(MAP_DEFAULT_SIZE);

    @Override
    public boolean saveUrlMap(String tinyUrl, String originalUrl) {
        urlMap.put(tinyUrl, originalUrl);
        return true;
    }

    @Override
    public Optional<String> getOriginalUrl(String tinyUrl) {
        String originalUrl = urlMap.get(tinyUrl);
        if (Objects.isNull(originalUrl)) {
            return Optional.empty();
        }
        return Optional.of(originalUrl);
    }

    @Override
    public Optional<String> getTinyUrl(String originalUrl) {
        for (Map.Entry<String, String> kv : urlMap.entrySet()) {
            String savedOriginalUrl = kv.getValue();
            String savedTinyUrl = kv.getKey();
            if (Objects.equals(originalUrl, savedOriginalUrl)) {
                return Optional.of(savedTinyUrl);
            }
        }
        return Optional.empty();
    }
}
